/// <reference path="Application_koViewModel.g.js" />
/// <reference path="../Scripts/jquery-1.7.1.min.js" />
/// <reference path="../Scripts/knockout-2.1.0.js" />
function ApplicationViewModel() {
    var self = this;
    // put a property loop here
    self.ApplicationID = ko.observable();
    self.ApplicationName = ko.observable();
    self.TS = ko.observable();
    self.CreatedBy = ko.observable();
    self.CreatedDt = ko.observable();
    self.ModifiedBy = ko.observable();
    self.ModifiedDt = ko.observable();
    self.Action = ko.observable();
    self.Caller = ko.observable();
    self.Role = ko.observable();
    self.PageSize = ko.observable();
    self.PageNumber = ko.observable();
    self.SortColumn = ko.observable();
    self.SortType = ko.observable();
    self.TotalRows = ko.observable();

    self.AddApplication = ko.observable();
    
    self.mySelectedApp= ko.observable()

    self.ApplicationList = ko.observableArray([]);
    self.setApplication = function (
			_ApplicationID, _ApplicationName, _TS, _CreatedBy, _CreatedDt, _ModifiedBy, _ModifiedDt, _Action, _Caller, _Role, _PageNumber, _PageSize, _SortColumn, _SortType, _TotalRows

	) {

        self.ApplicationID = _ApplicationID;
        self.ApplicationName = _ApplicationName;
        self.TS = _TS;
        self.CreatedBy = _CreatedBy;
        self.CreatedDt = _CreatedDt;
        self.ModifiedBy = _ModifiedBy;
        self.ModifiedDt = _ModifiedDt;
        self.Action = _Action;
        self.Caller = _Caller;
        self.Role = _Role;
        self.PageSize = _PageSize
        self.PageNumber = _PageNumber;
        self.SortColumn = _SortColumn;
        self.SortType = _SortType;
        self.TotalRows = _TotalRows;

    }; //  End of set procedure 

   

    //Add Application
    self.getAppID = function () {
        var self = this;
        //alert("We are in the AddApplication ko function");

        self.Action = "Add";
        self.Caller = "trooks";
        self.Role = "user";
        
       
        jQuery.ajax({
            url: "./api/ApplicationAPI/",
            data: ko.toJSON({ ApplicationName: self.ApplicationName, Action: self.Action, Caller: self.Caller }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                //alert(result);
                $('#myModaladd').modal('hide');
                self.GetApplicationByParameter();

            }
        });



    }; //End of add procedure

    self.Apps = ko.observableArray([]);

    self.SelectedApps = ko.observable();

    function passItem(id, name) {
        this.ApplicationID = ko.observable(id);
        this.ApplicationName = ko.observable(name);

    }

    self.searchApp = function (data, event) {
        //var self = this;
        if (event.keyCode == 13) {
            //alert("Selected Application" + "--" + self.SelectedApps().ApplicationID);

            jQuery.ajax({
                url: "./account/SetApplication/",
                data: ko.toJSON({ AppID: self.mySelectedPerson().ApplicationID }),
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    alert(result);
                    
                }
            });
        }
        return true;
    }
  
    

    self.GetApplicationByParameter = function () {
        //alert("We are inside of Get application by parameter funciton");
        self.Action = "GetAll";
        self.Caller = "trooks";
        self.Role = "user";
        self.PageNumber = 1;
        self.PageSize = 10;
        self.SortColumn = "ApplicationID";
        self.SortType = "asc";
        jQuery.ajax({
            url: "./api/ApplicationAPI/",
            data: { Action: self.Action, Caller: self.Caller, Role: self.Role, PageNumber: self.PageNumber, PageSize: self.PageSize, SortColumn: self.SortColumn, SortType: self.SortType },
            type: 'GET',
            success: function (result) {
                self.ApplicationList.removeAll();
                $.each(result, function (key, val) {
               
                    self.ApplicationList.push(
                        val
                    )
                })
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //alert(ajaxOptions);
            //alert(xhr.status);
            //alert(thrownError);
            $('#SearchFilter-home').css({ 'display': 'none' });
        }
    });

        

    };






    ko.bindingHandlers.jqAuto = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var options = valueAccessor() || {},
                allBindings = allBindingsAccessor(),
                unwrap = ko.utils.unwrapObservable,
                modelValue = allBindings.jqAutoValue,
                source = allBindings.jqAutoSource,
                valueProp = allBindings.jqAutoSourceValue,
                inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
                labelProp = allBindings.jqAutoSourceLabel || valueProp;

            //function that is shared by both select and change event handlers
            function writeValueToModel(valueToWrite) {
                if (ko.isWriteableObservable(modelValue)) {
                    modelValue(valueToWrite);
                } else {  //write to non-observable
                    if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue'])
                        allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite);
                }
            }

            //on a selection write the proper value to the model
            options.select = function (event, ui) {
                writeValueToModel(ui.item ? ui.item.actualValue : null);
            };

            //on a change, make sure that it is a valid value or clear out the model value
            options.change = function (event, ui) {
                var currentValue = $(element).val();
                var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
                    return unwrap(item[inputValueProp]) === currentValue;
                });

                if (!matchingItem) {
                    writeValueToModel(null);
                }
            }


            //handle the choices being updated in a DO, to decouple value updates from source (options) updates
            var mappedSource = ko.dependentObservable(function () {
                mapped = ko.utils.arrayMap(unwrap(source), function (item) {
                    var result = {};
                    result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString();  //show in pop-up choices
                    result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString();  //show in input box
                    result.actualValue = valueProp ? unwrap(item[valueProp]) : item;  //store in model
                    return result;
                });
                return mapped;
            }, null, { disposeWhenNodeIsRemoved: element });

            //whenever the items that make up the source are updated, make sure that autocomplete knows it
            mappedSource.subscribe(function (newValue) {
                $(element).autocomplete("option", "source", newValue);
            });

            options.source = mappedSource();

            //initialize autocomplete
            $(element).autocomplete(options);
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            //update value based on a model change
            var allBindings = allBindingsAccessor(),
                unwrap = ko.utils.unwrapObservable,
                modelValue = unwrap(allBindings.jqAutoValue) || '',
                valueProp = allBindings.jqAutoSourceValue,
                inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;

            //if we are writing a different property to the input than we are writing to the model, then locate the object
            if (valueProp && inputValueProp !== valueProp) {
                var source = unwrap(allBindings.jqAutoSource) || [];
                var modelValue = ko.utils.arrayFirst(source, function (item) {
                    return unwrap(item[valueProp]) === modelValue;
                }) || {};  //probably don't need the || {}, but just protect against a bad value          
            }

            //update the element with the value that should be shown in the input
            $(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());
        }
    };


 

    

    self.myOptions = ko.observableArray([]),
    

    function Item(id, name) {
        //var self = this;
        
        return {
            id: ko.observable(id),
            name: ko.observable(name)

        };
    }

   



   



















}; //End of view model








